package com.tg.app.activity.device.add;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;

import com.tg.app.R;
import com.base.BaseFragment;
import com.tange.base.toolkit.WifiAp;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tange.base.toolkit.NetworkUtil;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.SoundPlayerManager;


public class QRCodeAddFragment extends BaseFragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    public static final String TAG = "QRCodeAddFragment";
    private Activity mActivity;
    private EditText wifiNameEditText, wifiPasswordEditText;
    private Button nextStep;

    private ImageButton clearWifiPwdBtn;
    private CheckBox seaPwdCheck;
    private OnAddDeviceListener listener;
    private   WifiAp  wifiAp;

    private SoundPlayerManager soundPlayerManager;

    private final Handler uiHandler = new Handler(Looper.getMainLooper());


    public QRCodeAddFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_qrcode_add, container, false);
        mActivity = getActivity();
        initView(view);
        return view;
    }

    private void initView(View view) {
        wifiNameEditText = view.findViewById(R.id.wifi_name);
        view.findViewById(R.id.wifi_ls).setOnClickListener(this);
        wifiPasswordEditText = view.findViewById(R.id.wifi_password);
        nextStep = view.findViewById(R.id.next_step);
        nextStep.setOnClickListener(this);
        clearWifiPwdBtn = view.findViewById(R.id.cleanpwd);
        clearWifiPwdBtn.setOnClickListener(this);
        seaPwdCheck = view.findViewById(R.id.seapwd);

        seaPwdCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    wifiPasswordEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    wifiPasswordEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                int position = wifiPasswordEditText.getText().toString().trim().length();
                if (position > 0){
                    wifiPasswordEditText.setSelection(position);
                }
            }
        });
        wifiPasswordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    clearWifiPwdBtn.setVisibility(View.VISIBLE);
                    seaPwdCheck.setVisibility(View.VISIBLE);
                    nextStep.setEnabled(true);
                } else {
                    clearWifiPwdBtn.setVisibility(View.GONE);
                    seaPwdCheck.setVisibility(View.GONE);
                    if (wifiAp!=null&& wifiAp.enctype ==1){
                        nextStep.setEnabled(false);
                    }
                }
            }
        });
        wifiNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.length() > 0) {
                    nextStep.setEnabled(true);
                } else {
                    nextStep.setEnabled(false);
                }
            }
        });
    }

    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }


    @Override
    public void onResume() {
        super.onResume();
        wifiNameEditText.setText("");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PermissionUtil permissionUtil = new PermissionUtil(getActivity());

            if (permissionUtil.check(android.Manifest.permission.ACCESS_FINE_LOCATION) &&
                    permissionUtil.check(android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
                getWifiSSID();
                playSound(DeviceAddSoundConstants.WifiChoose(getActivity()));
            } else {
                permissionUtil.showDialog(getResources().getString(R.string.permission_settings_title), getResources().getString(R.string.permission_settings_location));
            }
        } else {
            getWifiSSID();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseSound();
    }

    private void pauseSound() {
        uiHandler.removeCallbacksAndMessages(null);
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
    }

    private void playSound(String url) {
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
        if (getActivity() == null) return;
        soundPlayerManager = SoundPlayerManager.create(getActivity());
        uiHandler.postDelayed(() -> {
            if (getActivity() == null) return;
            if (soundPlayerManager != null) {
                soundPlayerManager.download(url, true);
            }
        }, 1000);
    }

    private void getWifiSSID() {
        if (TextUtils.isEmpty(wifiNameEditText.getText())) {
            wifiAp  = NetworkUtil.getConnectWifiSSID(getContext());
            wifiNameEditText.setText(wifiAp.ssid);
            if (wifiAp.enctype ==1){
                nextStep.setEnabled(false);
            }else {
                nextStep.setEnabled(true);
            }
        }
    }


    private void getWifi() {
        Intent intent = new Intent();
        intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
        startActivity(intent);
    }


    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override

    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.next_step) {
            String ssi = wifiNameEditText.getText().toString();
            String pwd = wifiPasswordEditText.getText().toString();
            if (ssi.length() > 0 && listener != null) {/*&& pwd.length() > 0*/
                listener.onGenerateQRCode(ssi, pwd, null);
            }
        } else if (id == R.id.cleanpwd) {
            wifiPasswordEditText.setText("");
        } else if (id == R.id.wifi_ls) {
            getWifi();
        }
    }
}
